import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
import { h } from 'vue'
const routes = [
  {
    name: 'default',
    path: '/',
    redirect: { name: 'layout' }
  },
  // 配置一级路由---公共部分
  {
    path: '/',
    name: 'layout',
    component: () => import('@/views/layout.vue'),
    redirect: { name: 'home' },
    // 添加子路由
    children: [
      // 首页
      {
        name: 'home',
        path: 'home',
        component: () => import('@/views/home/index.vue')
      },
      // 一级菜单页面
      {
        name: 'category',
        path: 'category/:id',
        component: () => import('@/views/category/index.vue')
      },
      // 二级菜单页面
      {
        name: 'category/sub',
        path: 'category/sub/:id',
        component: () => import('@/views/category/sub.vue')
      },
      // 商品详情页
      {
        name: 'product',
        path: '/product/:id',
        component: () => import('@/views/goods/index.vue')
      },
      // 购物车页面
      {
        name: 'cart',
        path: '/cart',
        component: () => import('@/views/cart/index.vue')
      },
      // 结算页面
      {
        name: 'memberCheckout',
        path: '/member/checkout',
        component: () => import('@/views/member/pay/checkout')
      },
      // 支付页面
      {
        name: 'memberPay',
        path: 'member/pay',
        component: () => import('@/views/member/pay/index.vue')
      },
      // 支付完之后的跳转页面
      {
        name: 'payCallback',
        path: 'pay/callback',
        component: () => import('@/views/member/pay/callback.vue')
      },
      // 个人中心页面
      {
        name: 'member',
        path: '/member',
        component: () => import('@/views/member/Layout.vue'),
        children: [
          {
            path: '/member',
            component: () => import('@/views/member/home/index.vue')
          },
          {
            path: '/member/order',
            // vue3.0 需要有嵌套关系才能模糊匹配
            component: { render: () => h(<RouterView />) },
            children: [
              { path: '', component: () => import('@/views/member/order') },
              { path: ':id', component: () => import('@/views/member/order/detail') }
            ]
          }
        ]
      }

    ]
  },
  // 登录页
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  },
  // qq登录回跳页
  {
    path: '/login/callback',
    name: 'Callback',
    component: () => import('@/views/login/callback.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior (to, from, savedPosition) {
    // 始终滚动到顶部
    return { top: 0 }
  }
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // 用户信息
  const { token } = store.state.user.profile
  // 没有token并且去以/member开头的地址
  if (to.path.startsWith('/member') && !token) {
    next({ path: '/login', query: { redirectUrl: to.fullPath } })
  }
  next()
})
export default router
